<template>
  <el-container>
    <el-container>
      <el-card shadow="always" class="cardBlock">
        <div slot="header" class="clearfix">
          <span>试用套餐</span>
        </div>
        <el-form :model="form" ref="form" :rules="rules" style="height:auto;margin:50px auto" label-position="right" label-width="150px">
          <el-form-item label="套餐名称" prop="mealName">
            <el-input v-model="form.mealName" style="width: 300px;"></el-input>
          </el-form-item>
          <el-form-item label="有效期" prop="terOfValidity">
            <el-input placeholder="有效期" v-model="form.terOfValidity" class="input-with-select" maxlength="3" style="width: 300px;">
              <el-select style="width: 80px" v-model="form.dictTerOfValidity" slot="append" placeholder="单位">
                <el-option label="月" value="MONTH"></el-option>
                <el-option label="天" value="DAY"></el-option>
              </el-select>
              <el-button></el-button>
            </el-input>
          </el-form-item>
          <el-form-item label="流量" prop="mealSpec">
            <el-input placeholder="流量" v-model="form.mealSpec" maxlength="7" class="input-with-select" style="width: 300px;">
              <el-select style="width: 80px" v-model="form.mealSpecUnit" slot="append" placeholder="单位">
                <el-option label="MB" value="MB"></el-option>
                <el-option label="GB" value="GB"></el-option>
              </el-select>
              <el-button></el-button>
            </el-input>
          </el-form-item>
          <el-form-item label="官方售价" prop="officialPrice">
            <el-input v-model="form.officialPrice" maxlength="7" style="width: 300px">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="OEM成本价" prop="oemCostPrice">
            <el-input v-model="form.oemCostPrice" maxlength="7" style="width: 300px">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="代理最高售价" prop="ceilingPrice">
            <el-input v-model="form.ceilingPrice" maxlength="7" style="width: 300px">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="权限值" prop="cardFlowImaginary">
            <el-input-number v-model="form.cardFlowImaginary" :precision="2" :step="0.1" :max="999" style="width: 200px;"></el-input-number>
          </el-form-item>
          <el-form-item label="上游套餐编号" prop="thirdId">
            <el-input v-model="form.thirdId" style="width: 300px;"></el-input>
          </el-form-item>
          <el-form-item label="限制充值次数" prop="num">
            <el-input v-model="form.num" style="width: 300px;"></el-input>
          </el-form-item>
          <el-form-item label="排序" prop="seq">
            <el-input v-model="form.seq" maxlength="4" style="width: 300px;"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit('form')">提交</el-button>
            <el-button @click="resetForm('form')">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-container>
  </el-container>
</template>
<script>
import { is2PoinFloat,isNumber } from '../../../utils/validate'
import { getSetMeal, packageconserve } from '../../../api/getData'
export default {
  data() {
    const validateNum = (rule, value, callback) => {
      if (!is2PoinFloat(value)) {
        callback(new Error('请输入非负数，且保留小数点后两位'))
      } else {
        callback()
      }
    };
    const validateFlow = (rule, value, callback) => {
      if (!isNumber(value)) {
        return callback(new Error('请输入正整数'))
      } else {
        if(value>rule.max||value<rule.min){
          return callback(new Error(`最大值${rule.max}，最小值${rule.min}`))
        }
        callback()
      }
    };
    const validateDate = (rule, value, callback) => {
      if (!isNumber(value)) {
        return callback(new Error('请输入正整数'))
      } else {
        if(this.form.dictTerOfValidity=='DAY'){
          if(value>360||value<1){
            return callback(new Error(`最大值360，最小值1`))
          }
        }
        if(this.form.dictTerOfValidity=='MONTH'){
          if(value>12||value<1){
            return callback(new Error(`最大值12，最小值1`))
          }
        }
        callback()
      }
    };
    return {
      id: '',
      headId: '',
      headName: '',
      loading: false,
      form: {
        mealName: '',
        terOfValidity: '',
        dictTerOfValidity: 'MONTH',
        mealSpec: '',
        mealSpecUnit: 'GB',
        cardFlowImaginary: '',
        officialPrice: '',
        oemCostPrice: '',
        ceilingPrice: '',
        thirdId: '',
        num: '',
        dictMealType: 'TRY_MEAL',
      },
      rules: {
        mealName: [
          {required: true, message: '请输入套餐名称', trigger: 'blur'},
          {min: 3, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur'}
        ],
        terOfValidity: [
          {required: true, message: '请输入有效期', trigger: 'blur'},
          {validator: validateDate, min: 1, max: 36, trigger: 'blur'},
        ],
        mealSpec: [
          {required: true, message: '请输入流量', trigger: 'blur'},
          {validator: validateFlow, min: 1, max: 9999999, trigger: 'blur'}
        ],
        officialPrice: [
          {required: true, message: '请输入官方售价', trigger: 'blur'},
          {validator: validateNum, min: 0.1, max: 5000, trigger: 'blur'}
        ],
        ceilingPrice: [
          {required: true, message: '请输入代理售价上限', trigger: 'blur'},
          {validator: validateNum, min: 0.1, max: 5000, trigger: 'blur'}
        ],
        oemCostPrice: [
          {required: true, message: '请输入代OEM成本价', trigger: 'blur'},
          {validator: validateNum, min: 0.1, max: 5000, trigger: 'blur'}
        ],
        cardFlowImaginary: [
          {required: true, message: '请输入权限值', trigger: 'blur'},
          {pattern: validateNum, message: '请填写正确的权限值,保留两位小数'}
        ],
        seq: [
          {required: true, message: '请输入排序序号', trigger: 'blur'},
          {validator: validateFlow, min: 1, max: 5000, trigger: 'blur'}
        ],
      }
    }
  },
  mounted() {
    this.id = this.$router.query.id?this.$router.query.id:'';
    this.headId = this.$route.query.headId?this.$route.query.headId:'';
    this.headName = this.$route.query.headName;
    if(this.id){
      this.initData()
    }
  },
  methods: {
    async initData(){
      let s = await getSetMeal({id: this.id});
      if(s._result||s.code==10000){
        let mealSpec = s.data.mealSpec;
        let mealSpecUnit = 'MB';
        if (s.data.mealSpec >= 1024) {
          mealSpecUnit = 'GB';
          mealSpec = parseFloat(s.data.mealSpec / 1024).toFixed(2);
        }
        this.form = {
          mealName: s.data.mealName,//套餐名称
          terOfValidity: s.data.terOfValidity + '',//有效期
          dictTerOfValidity: s.data.dictTerOfValidity + '',//有效期单位
          mealSpec: mealSpec,//流量
          mealSpecUnit: mealSpecUnit,//流量单位
          thirdId: s.data.thirdId,//上游套餐编号
          cardFlowImaginary: s.data.cardFlowImaginary,//权限值
          officialPrice: s.data.officialPrice,//官方售价(元)
          ceilingPrice: s.data.ceilingPrice,//代理售价上限(元)
          oemCostPrice: s.data.oemCostPrice,//OEM成本价
          num: s.data.num,
        }

      }
    },
    onSubmit(formName){
      if (this.form.officialPrice * 1 < this.form.oemCostPrice * 1) {
        this.$message.error("官方售价不能低于OEM成本价！");
        return;
      }
      if (this.form.ceilingPrice * 1 < this.form.oemCostPrice * 1) {
        this.$message.error("代理设置的上限价格不能低于OEM成本价！");
        return;
      }
      if (this.form.ceilingPrice * 1 < this.form.officialPrice * 1) {
        this.$message.error("代理设置的上限价格不能低于官方售价！");
        return;
      }
      this.loading = true;
      this.$refs[formName].validate(valid=>{
        if(valid){
          let mealSpec = this.form.mealSpecUnit === 'GB' ? this.form.mealSpec * 1024 : this.form.mealSpec;
          let cardFlowImaginary = this.headName !== 'TONGYONG_HEAD' ? this.form.cardFlowImaginary : 0;//权限值
          let form = {
            dictMealType: this.form.dictMealType,				            //套餐类型
            dictSetMealGroupType: this.headName,                		//套餐大类
            headId: this.headId,								                    //套餐大类id
            id: this.id,									                          //套餐id
            mealName: this.form.mealName,								            //套餐名称
            mealSpec,         								                      //流量
            officialPrice: this.form.officialPrice,						      //官方售价(元)
            ceilingPrice: this.form.ceilingPrice,							      //代理售价上限(元)
            oemCostPrice: this.form.oemCostPrice,							      //OEM成本价
            seq: this.form.seq,									                    //排序
            cardFlowImaginary,                  						        //权限值 / 虚值
            terOfValidity: this.form.terOfValidity,						      //有效期
            dictTerOfValidity: this.form.dictTerOfValidity,         //有效期类型 月 / 日
            thirdId: this.form.thirdId,                             //上游套餐编号
          };
          packageconserve(form, {pagekey: this.pagekey});
          this.$message.success("套餐初始化中，请稍后查看");
          this.loading = false;
          setTimeout(() => {
            this.$router.back(-1);
          }, 1000);
        }
        else {
          this.loading = false;
          return false;
        }
      })
    },
    resetForm(formName){
      this.$refs[formName].resetFields();
    }
  }
}
</script>
<style scoped>
.cardBlock {
  //display: flex;
  //justify-content: center;
  //align-items: center;
  margin: 50px auto;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
  width: 600px
}
</style>
